package org.inspursc.s0517.health.common.util;

import lombok.extern.slf4j.Slf4j;
import org.inspursc.s0517.health.common.entity.SysLog;
import org.inspursc.s0517.health.common.service.SysLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.util.Date;

/**
 * @author yuchu
 */
@Component
@Slf4j
public class LogUtil {

    /**
     * 登陆
     */
    private static final String LOGIN_FORMAT="%S于%S 登陆系统，登陆IP：%S";
    /**
     * 创建用户
     */
    private static final String CREATE_CUSTOMER="%S于%S 创建/修改用户【%S】，登陆IP：%S";
    /**
     * 创建报告
     */
    private static final String CREATE_REPORT="%S于%S ，创建调查报告【%S】，登陆IP：%S";

    @Autowired
    private SysLogService logService;

    /**
     * 创建登陆日志
     * @param request
     */
    public void createLog(HttpServletRequest request){
        int loginId=SpringSecurityUtils.getCurrentUser(request).getId();
        String loginUser=SpringSecurityUtils.getCurrentName(request);
        String loginIp=SpringSecurityUtils.getCurrentUserIp(request);
        String loginTime=DateFormat.getDateTimeInstance().format(new Date());
        String content=String.format(LOGIN_FORMAT,loginUser,loginTime,loginIp);
        logService.save(new SysLog(loginId,loginIp,new Date(),content));
        log.info(content);
    }

    /**
     *  创建生成用户的日志
     * @param request
     * @param customerName
     */
    public void createLog(HttpServletRequest request,String customerName){
        int loginId=SpringSecurityUtils.getCurrentUser(request).getId();
        String loginUser=SpringSecurityUtils.getCurrentName(request);
        String loginIp=SpringSecurityUtils.getCurrentUserIp(request);
        String loginTime=DateFormat.getDateTimeInstance().format(new Date());
        String content=String.format(CREATE_CUSTOMER,loginUser,loginTime,customerName,loginIp);
        logService.save(new SysLog(loginId,loginIp,new Date(),content));
        log.info(content);
    }

    /**
     * 创建报告生成日志
     * @param request
     */
    public void createLog(HttpServletRequest request,String customerName,String reportName){
        int loginId=SpringSecurityUtils.getCurrentUser(request).getId();
        String loginIp=SpringSecurityUtils.getCurrentUserIp(request);
        String loginTime=DateFormat.getDateTimeInstance().format(new Date());
        String content=String.format(CREATE_REPORT,customerName,loginTime,reportName,loginIp);
        logService.save(new SysLog(loginId,loginIp,new Date(),content));
        log.info(content);
    }
}
